#!/usr/bin/env python
#coding=utf8
import sys, os, getopt, thread
import Log, Getconfig, cmrhelper
from cmrhelper import UtfToGbk, GbkToUtf8


global End

def DownloadStart(piclist, savepath, wgetpath, mangaconfig):
    global End
    for i in piclist:
        Download(i, savepath, wgetpath, mangaconfig)
    End = True
    print 'donwload finish.'

def Download(picitem, savepath, wgetpath, config):
    url = picitem[0]
    referer = picitem[1]
    chaptername = picitem[2]
    manganame = picitem[3]
    # gbk for windows ,utf-8 for linux file system
    # rough code ^_^
    spath = os.path.join(savepath, manganame, chaptername)
    if config.win:
        spath = UtfToGbk(spath)
    if os.path.isfile(os.path.join(spath, url[url.rfind('/')+1:])):
        # exist
        print os.path.join(spath, url[url.rfind('/')+1:]),'exists, abort.'
        return
    else:
        # dostr = "\"%s\" \"%s\" -q --referer=\"%s\" -P \"%s\"" % (self.config.wgetpath, url, referer, spath)
        dostr = "%s \"%s\" -t 5 -T 5 --referer=\"%s\" -P \"%s\"" %\
            (wgetpath, url, referer, spath)
        # print dostr
        os.system(dostr)
        # print os.path.join(spath, url[url.rfind('/')+1:]), 'download.'

if __name__ == '__main__':
    savepath = ''
    wgetpath = ''
    global End
    End = False
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'p:w:')
        if len(args) != 1:
            raise
        for o, a in opts:
            if o == '-p':
                savepath = a
            if o == '-w':
                wgetpath = a
        piclistpath = args[0]
    except  Exception, e:
        print 'usage: ./Fetch.py [-p savepath] [-w wgetpath] PicList'
        sys.exit()
    
    try:
        mangaconfig = Getconfig.Getconfig()
        mangalog = Log.Log(mangaconfig)
    except  Exception, e:
        print 'init global class fail'
        sys.exit()
    
    if wgetpath == '':
        wgetpath = mangaconfig.wgetpath
    if savepath == '':
        savepath = mangaconfig.savepath
        
    piclist = []
    try:
        picfile = open(piclistpath,'r')
        while True:
            line = picfile.readline()
            if not line:
                break
            item = line.split('\t')
            piclist.append([item[0], item[1], item[2], item[3]])
        picfile.close()        
    except  Exception, e:
        if not picfile.closed:
            picfile.close()
        mangalog.writeLog('open file error','fatal')
        sys.exit()
    try:
        thread.start_new_thread(DownloadStart,\
                                    (piclist, savepath, wgetpath, mangaconfig))
    except  Exception, e:
        mangalog.writeLog('Download error ' + str(e), 'error')
        sys.exit()
        
    while True:
        print 'type Ctrl+D or \'exit\' to end the Download.'
        input = sys.stdin.readline()
        if (not input) or (input.find('exit') != -1) or End:
            break
    
    mangalog.writeLog('exit.')
    sys.exit()
